﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;

public partial class UserControl_ControlMatHang : System.Web.UI.UserControl
{
    
    ClassExecute.ClassExecute dt;
    string str = webapp4U.Configuration.CurrentConnectionString;
    string error = "";
   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (ViewState["flag"] == null)
            {
                //ViewState["flag"] = false;
                ClearAdd();
            }
            ThreadStart thr1 = new ThreadStart(LoadProductNew);
            ThreadStart thr2 = new ThreadStart(LoadNganhHang);

            Thread tr1 = new Thread(thr1);
            Thread tr2 = new Thread(thr2);

            tr1.Start();
            tr2.Start();
            tr1.Join();
            tr2.Join();

            LoadNhanHieu(ddlNganhHang.SelectedValue.ToString());
           // BindDropGroupGridView();

        }
    }
    void ShowMessageBox(string text)
    {
        MessageBox.Text = text;
        MessageBox.ShowOnPageLoad = true;
    } 
    void LoadNhanHieu(String CatID)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "[k_getInclassFilter]", CommandType.StoredProcedure,
                new SqlParameter("@CatID",CatID));
            dt.BindDropDownList(db, ddlNhanHieu, "MaNhanHieu", "NhanHieu");
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    void LoadNganhHang()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "[ls_getCategoryList]", CommandType.StoredProcedure);
            dt.BindDropDownList(db, ddlNganhHang, "CommodKey", "Description");
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    void ClearAdd()
    {
        TabContainer1.ActiveTabIndex = 0;
        txtMaSo.Focus();
        txtDescription.Text = "";
       
        txtExtendedCode.Text = "";
        txtMaSo.Text = "";
       
        txtPrice.Text = "";

        txtUnit.Text = "";
        ViewState["flag"] = true;

        btnSave.Text = "Lưu";
        lblMsg.Text = "";
        lblMsg.Visible = false;
    }
    protected void imgBtnAdd_Click(object sender, ImageClickEventArgs e)
    {
        ClearAdd();        
    }   
    protected void grvMatHang_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvMatHang.PageIndex = e.NewPageIndex;
        LoadGrid();
    }
    protected void grvMatHang_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            if (e.CommandName == "chon")
            {
                GridViewRow grv = ((Control)e.CommandSource).NamingContainer as GridViewRow;
                Label lblMaSo = (Label)grv.FindControl(DRMConstants.CONTROL_NAME_LABEL_MASO);

                DataTable db = dt.Get_Data_DataTable(str, ref error, "[k_getDetailItemInfo]", CommandType.StoredProcedure,
                    new SqlParameter("@itemkey", lblMaSo.Text));
                txtMaSo.Text = db.Rows[0]["itemkey"].ToString();
                txtDescription.Text = db.Rows[0]["Description"].ToString();
                txtExtendedCode.Text = db.Rows[0]["smscode"].ToString();
                txtUnit.Text = db.Rows[0]["QuyCach"].ToString();

              
                try
                {
                    ddlNganhHang.SelectedValue = db.Rows[0]["commodkey"].ToString();
                    LoadNhanHieu(ddlNganhHang.SelectedValue.ToString());
                   
                }
                catch
                {
                }
                try
                {
                    ddlNhanHieu.SelectedValue = db.Rows[0]["inclasskey"].ToString();
                }
                catch
                {
                }
                try
                {
                    DropDistributor.SelectedValue = db.Rows[0]["Sitecode"].ToString();
                }
                catch
                {
                }
                chkActive.Checked = bool.Parse(db.Rows[0]["Active"].ToString());
                txtPrice.Text = db.Rows[0]["Price"].ToString();
               
               
               

                lblMsg.Text = "";
                lblMsg.Visible = false;
                btnSave.Text = "Cập nhật";

                grvMatHang.DataSource = null;
                grvMatHang.DataBind();

                ViewState["flag"] = false;
                TabContainer1.ActiveTabIndex = 0;
            }
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        LoadGrid();
    } 
    private void LoadGrid()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "k_searchItem", CommandType.StoredProcedure,
                new SqlParameter("@para", txtSearch.Text));

            if (db.Rows.Count > 0)
            {
                grvMatHang.DataSource = db;

            }
            else
            {
                grvMatHang.DataSource = null;
                ShowMessageBox("Không tìm thấy kết quả");
             
            }
            grvMatHang.DataBind();
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void ddlNganhHang_SelectedIndexChanged(object sender, EventArgs e)
    {
       
            LoadNhanHieu(ddlNganhHang.SelectedValue.ToString());
            
       
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        int i = 3;
        if (txtPrice.Text == "")
        {
            txtPrice.Text = "0";
        }

        try
        {
            if ((bool)ViewState["flag"])
            {
                //insert
                i = dt.ExecuteSQl_int(str, "k_insertProduct", CommandType.StoredProcedure, ref error,
                            new SqlParameter("@itemkey", txtMaSo.Text.Trim()),
                            new SqlParameter("@Description", txtDescription.Text),
                            new SqlParameter("@Price",float.Parse(txtPrice.Text)),
                            new SqlParameter("@Sitecode",DropDistributor.SelectedValue.ToString()),
                            new SqlParameter("@QuyCach",txtUnit.Text),
                            new SqlParameter("@smscode", txtExtendedCode.Text),
                            new SqlParameter("@inclasskey",ddlNhanHieu.SelectedValue.ToString()),
                            new SqlParameter("@commodkey", ddlNganhHang.SelectedValue.ToString()));
                if (i == 1)
                {
                    //ShowMessageBox("Thêm mặt hàng mới thành công");
                    ClearAdd();
                    lblMsg.Text = "Thêm sản phẩm mới thành công";
                    lblMsg.Visible = true;
                }
                else if (i == 3)
                {
                    //ShowMessageBox("Mã hàng 1 bị trùng,đề nghị nhập mã khác");
                    lblMsg.Text = "Mã SKU bị trùng,đề nghị nhập mã khác";
                    lblMsg.Visible = true;
                }
                else
                {
                    //ShowMessageBox("Hệ thống đang bảo trì");
                    lblMsg.Text = "Hệ thống đang bảo trì";
                    lblMsg.Visible = true;
                }

                //ViewState["flag"] = false;


                //txtDescription.Text = "";
                //txtDescription1.Text = "";
                //txtExtendedCode.Text = "";
                //txtMaSo.Text = "";
                //txtMaSo1.Text = "";
                //txtPrice.Text = "";

                //txtUnit.Text = "";

            }
            else
            {
                //update
                i = dt.ExecuteSQl_int(str, "k_updateProduct", CommandType.StoredProcedure, ref error,
                            new SqlParameter("@itemkey", txtMaSo.Text.Trim()),
                            new SqlParameter("@Description", txtDescription.Text),
                            new SqlParameter("@Sitecode", DropDistributor.SelectedValue.ToString()),
                            new SqlParameter("@QuyCach", txtUnit.Text),
                            new SqlParameter("@smscode", txtExtendedCode.Text),
                            new SqlParameter("@inclasskey", ddlNhanHieu.SelectedValue.ToString()),
                            new SqlParameter("@commodkey", ddlNganhHang.SelectedValue.ToString()));
                if (i == 1)
                {
                    //ShowMessageBox("Cập nhật mặt hàng thành công");
                    lblMsg.Text = "Cập nhật sản phẩm thành công";
                    lblMsg.Visible = true;
                }
                else if (i == 3)
                {
                    lblMsg.Text = "Mã SKU không tồn tại trong hệ thống";
                    lblMsg.Visible = true;
                }
                else
                {
                    //ShowMessageBox("Hệ thống đang bảo trì");
                    lblMsg.Text = "Hệ thống đang bảo trì";
                    lblMsg.Visible = true;

                }
            }
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    void LoadProductNew()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getProductNew", CommandType.StoredProcedure);
            if (db.Rows.Count > 0)
            {
                grvSanPhamMoi.DataSource = db;
                
            }
            else
            {
                grvSanPhamMoi.DataSource = null;
               
            }
            grvSanPhamMoi.DataBind();
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void grvSanPhamMoi_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvSanPhamMoi.PageIndex = e.NewPageIndex;
        LoadProductNew();
    }
    protected void grvSanPhamMoi_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            if (e.CommandName == "chon")
            {
                GridViewRow grv = ((Control)e.CommandSource).NamingContainer as GridViewRow;
                Label lblMaSo = (Label)grv.FindControl(DRMConstants.CONTROL_NAME_LABEL_MASO);
                DropDownList drlNhomSanPham = grv.FindControl("DropGroupGrid") as DropDownList;
                DropDownList drlKenhSanPham = grv.FindControl("DropChannelGrid") as DropDownList;
                //ShowMessageBox(lblMaSo.Text + "_" + drlNhomSanPham.SelectedValue.ToString() + "_" + drlKenhSanPham.SelectedValue.ToString());
                
                int i = dt.ExecuteSQl_int(str, "k_insertProductNew", CommandType.StoredProcedure, ref error,
                           new SqlParameter("@itemkey", lblMaSo.Text.Trim()),
                           new SqlParameter("@inclasskey", drlKenhSanPham.SelectedValue.ToString()),
                           new SqlParameter("@commodkey", drlNhomSanPham.SelectedValue.ToString()));
                if (i == 1)
                {
                    ShowMessageBox("Thêm mặt hàng mới thành công");
                   
                }
                else if (i == 3)
                {
                    ShowMessageBox("Mã hàng 1 bị trùng,đề nghị nhập mã khác");
                   
                }
                else
                {
                    ShowMessageBox("Hệ thống đang bảo trì");
                   
                }
                LoadProductNew();
            }
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }

    void BindDropGroupGridView()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DropDownList drGroup =(DropDownList) grvSanPhamMoi.Controls[0].FindControl("DropGroupGrid");
            DataTable db = dt.Get_Data_DataTable(str, ref error, "[ls_getCategoryList]", CommandType.StoredProcedure);
            dt.BindDropDownList(db, drGroup, "CommodKey", "Description");
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
   
    protected void grvSanPhamMoi_RowDataBound1(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            dt = new ClassExecute.ClassExecute();

            // Display the Group.
            DropDownList drGroup = (DropDownList)e.Row.Controls[0].FindControl("DropGroupGrid");
            DataTable db = dt.Get_Data_DataTable(str, ref error, "[ls_getCategoryList]", CommandType.StoredProcedure);
            dt.BindDropDownList(db, drGroup, "CommodKey", "Description");
           

            // Display the Channel.
            DropDownList drChannel = (DropDownList)e.Row.Controls[0].FindControl("DropChannelGrid");
            DataTable db1 = dt.Get_Data_DataTable(str, ref error, "[k_getInclassFilter]", CommandType.StoredProcedure,
               new SqlParameter("@CatID", drGroup.SelectedValue.ToString()));
            dt.BindDropDownList(db1, drChannel, "MaNhanHieu", "NhanHieu");

        }
    }

   
    protected void DropGroupGrid_SelectedIndexChanged(object sender, EventArgs e)
    {
        //cách 1
        //DropDownList ddGroup = sender as DropDownList;
        // DropDownList ddChannel;
       
        // int i = 0;
        // foreach (GridViewRow row in grvSanPhamMoi.Rows)
        // {
        //     //Finding Dropdown control  
        //     ddChannel = row.Controls[i].FindControl("DropChannelGrid") as DropDownList;
        //     //Control ctrlchannel = row.FindControl("DropChannelGrid") as DropDownList;
        //     if (ddChannel != null)
        //     {
                 
        //         dt = new ClassExecute.ClassExecute();
        //         DataTable db1 = dt.Get_Data_DataTable(str, ref error, "[k_getInclassFilter]", CommandType.StoredProcedure,
        //           new SqlParameter("@CatID", ddGroup.SelectedValue.ToString()));
        //         dt.BindDropDownList(db1, ddChannel, "MaNhanHieu", "NhanHieu");
        //         break; 
                
        //     }
        //     i++;
        // }

        //cách 2
         GridViewRow row = (GridViewRow)((sender) as Control).NamingContainer;
         DropDownList drlNhomSanPham = ((sender) as DropDownList);
         DropDownList drlKenhSanPham = row.FindControl("DropChannelGrid") as DropDownList;

         dt = new ClassExecute.ClassExecute();
         DataTable db1 = dt.Get_Data_DataTable(str, ref error, "[k_getInclassFilter]", CommandType.StoredProcedure,
            new SqlParameter("@CatID", drlNhomSanPham.SelectedValue.ToString()));
         dt.BindDropDownList(db1, drlKenhSanPham, "MaNhanHieu", "NhanHieu");


    }
}